package com.hntx.joymusic;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.blankj.utilcode.utils.Utils;

import java.util.Stack;

import static com.hntx.joymusic.sytRetrofity.SytRetrofitBase.setCer;

public class MyApp extends Application {
    private static MyApp mInstance;
    private String TAG = "MyApp";
    private Stack<Activity> activities;
    private HomeKeyReceiver mHomeKeyReceiver;

    public static MyApp getInstance() {
        return mInstance;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public void onCreate() {
        super.onCreate();
        mInstance = this;
        Utils.init(this);
        initHomeKeyReceiver();
        setCer(getResources().openRawResource(R.raw.yun));
    }

    private void initHomeKeyReceiver() {
        mHomeKeyReceiver = new HomeKeyReceiver();
        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(mHomeKeyReceiver, filter);
    }

    public void addActivity(Activity activity) {
        if (activities == null) {
            activities = new Stack<Activity>();
        }
        if (activities.search(activity) == -1) {
            activities.push(activity);
        }
        Log.d(TAG, "activity stack size = " + activities.size());
        Log.d(TAG, "activitys  = " + activities.toString());
    }

    public void removeActivity(Activity activity) {
        if (activities != null && activities.size() > 0) {
            activities.remove(activity);
            Log.d(TAG, "removed activity: " + activity.getClass().getName());
        }
    }

    public void finishAllActivity() {
        if (activities != null && activities.size() > 0) {
            while (!activities.empty()) {
                Activity activity = activities.pop();
                if (activity != null) {
                    activity.finish();
                    Log.d(TAG, "finished activity: " + activity.getClass().getName());
                }
            }
            activities.clear();
            activities = null;
        }
    }

    public void exitApp() {
        unregisterReceiver(mHomeKeyReceiver);
        finishAllActivity();
        System.exit(0);
    }
}